/**
 * Get local IP Address
 */
var ip_address = (function getIPAdress() {
    var interfaces = require('os').networkInterfaces();
    for (var devName in interfaces) {
      var iface = interfaces[devName];
      for (var i = 0; i < iface.length; i++) {
        var alias = iface[i];
        if (
          alias.family === 'IPv4' &&
          alias.address !== '127.0.0.1' &&
          !alias.internal
        ) {
          return alias.address;
        }
      }
    }
})();
  
var gulp = require('gulp');
var pug = require('gulp-pug');
var less = require('gulp-less');
var livereload = require('gulp-livereload');
var webserver = require('gulp-webserver');
var plumber = require('gulp-plumber');

gulp.task('views', function buildHTML() {
    //convert pug to HTML
    return gulp.src('./src/*.pug')
    .pipe(plumber())
    .pipe(pug({
        pretty:true
    }))
    .pipe(gulp.dest('dist'))
    .pipe(livereload());;
});

gulp.task('less', function () {
  return gulp.src(['./src/*.less'])
    .pipe(plumber())
    .pipe(less())
    .pipe(gulp.dest('./dist'))
    .pipe(livereload());
});

gulp.task('scripts', function() {
    return gulp.src('./dist/*.js')
        .pipe(plumber())
        .pipe(livereload());
  });

// Webserver default host 8000
gulp.task('webserver', function() {
    gulp.src('./')
      .pipe(webserver({
        host: ip_address,
        livereload: true,
        directoryListing: true
      }));
  });

// Rerun the task when a file changes
gulp.task('watch', function() {
    livereload.listen({ start: true });
    gulp.watch('src/*.pug', ['views']);
    gulp.watch('src/*.less', ['less']);
    gulp.watch('dist/*.js', ['scripts']);
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['watch','views','less','webserver']);